﻿using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint.WorkflowActions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;

namespace Linxiao.SP.Workflow.AddCRMLead.Library
{
    /// <summary>
    /// A custom sharepoint designer action to add lead to Dynamics CRM servers
    /// </summary>
    public partial class AddCRMLeadActivity : System.Workflow.ComponentModel.Activity
    {
        /// <summary>
        /// Workflow context of the current workflow instance
        /// </summary>
        public static DependencyProperty __ContextProperty = System.Workflow.ComponentModel.DependencyProperty.Register("__Context",
            typeof(WorkflowContext), typeof(AddCRMLeadActivity));
        [Description("Context")]
        [Browsable(true)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
        public WorkflowContext __Context
        {
            get
            {
                return ((WorkflowContext)(base.GetValue(__ContextProperty)));
            }
            set
            {
                base.SetValue(__ContextProperty, value);
            }
        }

        /// <summary>
        /// Url of Organization Service of the target dynamics crm server
        /// </summary>
        public static DependencyProperty CRMOrganizationServiceUrlProperty = DependencyProperty.Register("CRMOrganizationServiceUrl",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("CRM Organization Service Url")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string CRMOrganizationServiceUrl
        {
            get
            {
                return ((string)(base.GetValue(CRMOrganizationServiceUrlProperty)));
            }
            set
            {
                base.SetValue(CRMOrganizationServiceUrlProperty, value);
            }
        }

        /// <summary>
        /// Service account of the target dynamics crm server
        /// </summary>
        public static DependencyProperty CRMServiceAccountProperty = DependencyProperty.Register("CRMServiceAccount",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("CRM Service Account")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string CRMServiceAccount
        {
            get
            {
                return ((string)(base.GetValue(CRMServiceAccountProperty)));
            }
            set
            {
                base.SetValue(CRMServiceAccountProperty, value);
            }
        }

        /// <summary>
        /// Title of the lead
        /// </summary>
        public static DependencyProperty LeadTitleProperty = DependencyProperty.Register("LeadTitle",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("LeadTitle")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string LeadTitle
        {
            get
            {
                return ((string)(base.GetValue(LeadTitleProperty)));
            }
            set
            {
                base.SetValue(LeadTitleProperty, value);
            }
        }

        /// <summary>
        /// Login username of the organization service
        /// </summary>
        public static DependencyProperty ServiceUsernameProperty = DependencyProperty.Register("ServiceUsername",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Service Login Username")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string ServiceUsername
        {
            get
            {
                return ((string)(base.GetValue(ServiceUsernameProperty)));
            }
            set
            {
                base.SetValue(ServiceUsernameProperty, value);
            }
        }

        /// <summary>
        /// Login password of the organization service
        /// </summary>
        public static DependencyProperty ServicePasswordProperty = DependencyProperty.Register("ServicePassword",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Service Login Password")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string ServicePassword
        {
            get
            {
                return ((string)(base.GetValue(ServicePasswordProperty)));
            }
            set
            {
                base.SetValue(ServicePasswordProperty, value);
            }
        }

        /// <summary>
        /// Domain of the login user
        /// </summary>
        public static DependencyProperty DomainProperty = DependencyProperty.Register("Domain",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Domain of the login user")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string Domain
        {
            get
            {
                return ((string)(base.GetValue(DomainProperty)));
            }
            set
            {
                base.SetValue(DomainProperty, value);
            }
        }

        /// <summary>
        /// First name of the lead
        /// </summary>
        public static DependencyProperty FirstNameProperty = DependencyProperty.Register("FirstName",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("First Name of the Lead")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string FirstName
        {
            get
            {
                return ((string)(base.GetValue(FirstNameProperty)));
            }
            set
            {
                base.SetValue(FirstNameProperty, value);
            }
        }

        /// <summary>
        /// Family name of the lead
        /// </summary>
        public static DependencyProperty FamilyNameProperty = DependencyProperty.Register("FamilyName",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Family Name of the Lead")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string FamilyName
        {
            get
            {
                return ((string)(base.GetValue(FamilyNameProperty)));
            }
            set
            {
                base.SetValue(FamilyNameProperty, value);
            }
        }

        /// <summary>
        /// Company name of the lead
        /// </summary>
        public static DependencyProperty CompanyNameProperty = DependencyProperty.Register("CompanyName",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Company Name of the Lead")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string CompanyName
        {
            get
            {
                return ((string)(base.GetValue(CompanyNameProperty)));
            }
            set
            {
                base.SetValue(CompanyNameProperty, value);
            }
        }

        /// <summary>
        /// Email of the lead
        /// </summary>
        public static DependencyProperty EmailProperty = DependencyProperty.Register("Email",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Email of the Lead")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string Email
        {
            get
            {
                return ((string)(base.GetValue(EmailProperty)));
            }
            set
            {
                base.SetValue(EmailProperty, value);
            }
        }

        /// <summary>
        /// Telephone of the lead
        /// </summary>
        public static DependencyProperty TelephoneProperty = DependencyProperty.Register("Telephone",
            typeof(string), typeof(AddCRMLeadActivity));
        [Description("Telephone of the Lead")]
        [Category("Custom")]
        [Browsable(true)]
        [DesignerSerializationVisibility
        (DesignerSerializationVisibility.Visible)]
        public string Telephone
        {
            get
            {
                return ((string)(base.GetValue(TelephoneProperty)));
            }
            set
            {
                base.SetValue(TelephoneProperty, value);
            }
        }
     

        public AddCRMLeadActivity()
        {
            InitializeComponent();
        }

        protected override ActivityExecutionStatus Execute(ActivityExecutionContext executionContext)
        {
            DynamicsCRMContext serviceContext=null;
            try
            {
                //if the encryption key-pair does not exist, generate encryption key-pair. 
                RSACryptoService.GetKeyFromContainer("LinxiaoKeyContainer", false);

                //Create a dynamics crm web services client
                serviceContext = new DynamicsCRMContext(CRMOrganizationServiceUrl, ServiceUsername, ServicePassword, Domain, CRMServiceAccount);
                //add a lead
                serviceContext.AddLead(LeadTitle, FirstName, FamilyName, Email, Telephone, CompanyName); 
                serviceContext.Dispose();
                return ActivityExecutionStatus.Closed;
            }
            catch (Exception ex)
            {
                Log(string.Format("Failed to add the lead through Dynamics Crm web services. {0}", ex.Message));
                if (serviceContext !=null)
                    serviceContext.Dispose();
                return ActivityExecutionStatus.Faulting;
            }
            
        }

        /// <summary>
        /// Log to workflow history
        /// </summary>
        /// <param name="message"></param>
        public void Log(string message)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWorkflow.CreateHistoryEvent(__Context.Web, __Context.WorkflowInstanceId, 0, __Context.Web.CurrentUser, new TimeSpan(), "AddCRMLeadActivity", message, string.Empty);
            });
        }

        
    }
}
